package com.elinkway.infinitemovies.push;

/**
 * 推送后台服务
 * */

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;

import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.async.MoviesHttpAsyncTask;
import com.elinkway.infinitemovies.bean.PushData;
import com.elinkway.infinitemovies.config.SettingManage;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi;
import com.elinkway.infinitemovies.http.parser.PushDataParser;
import com.elinkway.infinitemovies.utils.CDEManager;
import com.letv.pp.func.CdeHelper;
import com.lvideo.http.bean.LVideoDataHull;

public class PushService extends Service {

	private static final String TAG = PushService.class.getSimpleName();

	RetrieveTask task;
	WakeLock mWakeLock;

	@Override
	public void onCreate() {

		super.onCreate();
		PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
		mWakeLock.acquire();
		task = new RetrieveTask(this);
		task.start();
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onDestroy() {

		if (!task.isCancelled()) {
			task.cancel();
		}

		mWakeLock.release();

		super.onDestroy();
	}

	/**
	 * 启动推送
	 * */
	public static void schedule(Context context) {
//		if (!SettingManage.getInstance().isPush()) {
//			return;
//		}
//
//		//更新间隔
//		int interval = SettingManage.getInstance().getPushDistance() ;
//		long historyTime = SettingManage.getInstance().getPushTime() ;
//
//
//		Intent intent = new Intent(context,PushService.class);
//		PendingIntent pending = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
//
//		AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
//
//		alarm.cancel(pending);
//		alarm.set(AlarmManager.RTC_WAKEUP, (historyTime + interval * 1000), pending);
//		alarm.set(AlarmManager.RTC_WAKEUP, 20000, pending);
//		alarm.setRepeating(AlarmManager.RTC_WAKEUP,1000, 10000, pending);
	}

	/**
	 * 取消推送
	 * */
	public static void unschedule(Context context) {
//		Intent intent = new Intent(context, PushService.class);
//		PendingIntent pending = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
//		AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
//
//		alarm.cancel(pending);
	}

	/**
	 * 请求推送接口
	 * */
	class RetrieveTask extends MoviesHttpAsyncTask<PushData> {

		public RetrieveTask(Context context) {
			super(context);
		}

		@Override
		public LVideoDataHull<PushData> doInBackground() {
			long historyTime = SettingManage.getInstance().getPushTime();
			long curTime = System.currentTimeMillis();
			int distance = SettingManage.getInstance().getPushDistance();
			if (curTime - historyTime >= (distance - 10) * 1000) {
				SettingManage.getInstance().savePushTime(curTime);
				return MoviesHttpApi.requestPushData(new PushDataParser());
			}
			return null;
		}

		@Override
		public void onPostExecute(int updateId, PushData result) {
            if (result != null) {
                // 判断CDE服务是否已经准备好了
                CDEManager cdeManager = CDEManager.getInstance(MoviesApplication.getInstance());
                CdeHelper cdeHelper = cdeManager.getmCdeHelper();
                if (!cdeHelper.isReady()) {
                    cdeManager.startCde();
                }
                PushNotificationSender.sendNotify(PushService.this, result);
            }
            int distance = result.getFrequency();// 推送时间处理
            if (distance > 0) {
                SettingManage.getInstance().savePushDistance(distance);
            }
            schedule(PushService.this);
            stopSelf();
		}

		@Override
		public void preFail(){//不会进入doInBackground 方法，无法保存时间戳
			SettingManage.getInstance().savePushTime(System.currentTimeMillis());
			schedule(PushService.this);
			stopSelf();
		}

		@Override
		public void netNull() {//不会进入doInBackground 方法，无法保存时间戳
			SettingManage.getInstance().savePushTime(System.currentTimeMillis());
			schedule(PushService.this);
			stopSelf();
		};

		@Override
		public void netErr(int updateId, String errMsg) {
			schedule(PushService.this);
			stopSelf();
		};

		@Override
		public void dataNull(int updateId, String errMsg) {
			schedule(PushService.this);
			stopSelf();
		}

	}
}
